package com.ruoyi.business.service.wecom.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.dto.admin.wecom.WecomChatGroupWelAddDTO;
import com.ruoyi.business.domain.fission.TbWecomChatGroupWel;
import com.ruoyi.business.mapper.fission.TbWecomChatGroupWelMapper;
import com.ruoyi.business.service.wecom.ITbWecomChatGroupWelService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpGroupWelcomeTemplateResult;
import me.chanjar.weixin.cp.bean.external.msg.MiniProgram;
import me.chanjar.weixin.cp.bean.external.msg.Text;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 入群欢迎语 服务实现类
 * </p>
 *
 * @author
 * @since 2024-01-20
 */
@Service
@Slf4j
public class TbWecomChatGroupWelServiceImpl extends ServiceImpl<TbWecomChatGroupWelMapper, TbWecomChatGroupWel> implements ITbWecomChatGroupWelService {

    @Resource
    private WxCpService wxCpService;

    @Value("${wechat.miniapp.configs[0].appid}")
    private String appid;

    @Value("${wechat.cp.apps[0].agent-id}")
    private String agentId;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWecomWel(WecomChatGroupWelAddDTO wel) {
        // 调用企微 api
        WxCpGroupWelcomeTemplateResult template = new WxCpGroupWelcomeTemplateResult();
        Text text = new Text();
        text.setContent(wel.getTextContent());
        template.setText(text);
        MiniProgram miniProgram = new MiniProgram();
        miniProgram.setTitle(wel.getMiniprogramTitle());
        miniProgram.setPicMediaId(wel.getMiniprogramPicMediaId());
        miniProgram.setAppid(appid);
        miniProgram.setPage(Constants.MINI_APP_SHARE_PAGE);
        template.setMiniprogram(miniProgram);
        template.setNotify(wel.getNotify());
        String tempId;
        try {
            tempId = wxCpService.getExternalContactService().addGroupWelcomeTemplate(template);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        log.info("入群欢迎语创建成功，入群欢迎语id:{}", tempId);
        // 新增入群欢迎语数据
        TbWecomChatGroupWel tbWecomChatGroupWel = new TbWecomChatGroupWel();
        tbWecomChatGroupWel.setId(IdWorker.getId());
        tbWecomChatGroupWel.setAgentid(agentId);
        tbWecomChatGroupWel.setTemplateId(tempId);
        tbWecomChatGroupWel.setTextContent(wel.getTextContent());
        tbWecomChatGroupWel.setMiniprogramTitle(wel.getMiniprogramTitle());
        tbWecomChatGroupWel.setMiniprogramPicMediaId(wel.getMiniprogramPicMediaId());
        tbWecomChatGroupWel.setMiniprogramPicMinioUrl(wel.getMiniprogramPicUrl());
        tbWecomChatGroupWel.setMiniprogramAppid(appid);
        tbWecomChatGroupWel.setMiniprogramPage(Constants.MINI_APP_SHARE_PAGE);
        tbWecomChatGroupWel.setCreateTime(new Date());
        tbWecomChatGroupWel.setCreateBy(LoginHelper.getLoginUser().getUsername());
        return this.save(tbWecomChatGroupWel);
    }

    @Override
    public TableDataInfo<TbWecomChatGroupWel> sysPageQuery(PageQuery pageQuery) {
        LambdaQueryWrapper<TbWecomChatGroupWel> qwl = Wrappers.lambdaQuery(TbWecomChatGroupWel.class)
            .orderByDesc(TbWecomChatGroupWel::getCreateTime);
        Page<TbWecomChatGroupWel> page = this.page(pageQuery.build(), qwl);
        return TableDataInfo.build(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(Collection<Long> ids) {
        LambdaQueryWrapper<TbWecomChatGroupWel> qwl = Wrappers.lambdaQuery(TbWecomChatGroupWel.class).in(TbWecomChatGroupWel::getId, ids);
        List<TbWecomChatGroupWel> tbWecomChatGroupWels = this.list(qwl);
        if (CollectionUtils.isNotEmpty(tbWecomChatGroupWels)) {
            for (TbWecomChatGroupWel item : tbWecomChatGroupWels) {
                try {
                    wxCpService.getExternalContactService().delGroupWelcomeTemplate(item.getTemplateId(), item.getAgentid());
                } catch (WxErrorException e) {
                    log.error(e.getMessage(), e);
                    throw new RuntimeException(e);
                }
            }
        }
        return this.removeByIds(ids);
    }
}
